<template>
  <div id="retrievePasswordPage">
    <header class="resetPassword">重置密码</header>
    <div class="processBar">
      <el-steps :active="active" align-center>
        <el-step title="找回密码"></el-step>
        <el-step title="验证"></el-step>
        <el-step title="重置密码"></el-step>
      </el-steps>
    </div>
    <div class="content" v-if="active == 0">
      <div class="findPassword">
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item prop="userName">
            <el-input
              v-model="ruleForm.userName"
              placeholder="输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="code" class="randomCodeItem">
            <el-input
              class="code"
              v-model="ruleForm.code"
              placeholder="验证码"
            ></el-input>
            <!-- <span class="randomCode"></span> -->
            <canvas
              @click="resetCode"
              id="randomCode"
              width="150"
              height="40"
            ></canvas>
          </el-form-item>
        </el-form>
        <div class="bottomContainer">
          <p class="goLogin" @click="goLogin()">返回首页</p>
          <p class="nextStep" @click="nextStep('ruleForm', active)">下一步</p>
        </div>
      </div>
    </div>
    <div class="content" v-if="active == 1">
      <div class="findPassword">
        <el-form
          :model="ruleForm2"
          status-icon
          :rules="rules2"
          ref="ruleForm2"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item prop="phoneNumber">
            <el-input
              v-model="ruleForm2.phoneNumber"
              placeholder="输入账号"
              readonly
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="code">
            <el-input
              class="code"
              v-model="ruleForm2.code"
              placeholder="短信验证码"
            ></el-input>
            <el-button
              v-if="!isGetCode"
              class="getCode"
              type="info"
              plain
              @click="getPhoneCode"
              >免费获取验证码</el-button
            >
            <span class="countdown" v-else>{{ countdown }}s后重新获取</span>
          </el-form-item>
        </el-form>
        <div class="bottomContainer">
          <p class="goLogin" @click="goLogin()">返回首页</p>
          <p class="nextStep" @click="nextStep('ruleForm2', active)">下一步</p>
        </div>
      </div>
    </div>
    <div class="content" v-if="active == 2">
      <div class="findPassword">
        <el-form
          :model="ruleForm3"
          status-icon
          :rules="rules3"
          ref="ruleForm3"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="" prop="password">
            <el-input
              v-model="ruleForm3.password"
              placeholder="设置密码"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="confirmPassword">
            <el-input
              v-model="ruleForm3.confirmPassword"
              placeholder="确认密码"
              show-password
            ></el-input>
          </el-form-item>
        </el-form>
        <div class="bottomContainer">
          <p class="goLogin" @click="goLogin()">返回首页</p>
          <p class="nextStep" @click="nextStep('ruleForm3', active)">
            重置密码
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getCode,
  register,
  verifyUser,
  verifyUserCode,
  resetPassword,
} from "@/apis/common.js";
export default {
  data() {
    return {
      active: 0, //当前步骤
      // 步骤一
      ruleForm: {
        userName: "", //账号
        code: "", //验证码
      },
      // 步骤二
      ruleForm2: {
        phoneNumber: "", //账号
        code: "", //验证码
      },
      // 步骤三
      ruleForm3: {
        password: "", //密码
        confirmPassword: "", //确认密码
      },
      randomCode: "", //生成的随机验证码
      rules: {
        // userName: [
        //   { required: true, message: "请输入用户名称", trigger: "blur" },
        // ],
        // code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      rules2: {
        // userName: [
        //   { required: true, message: "请输入手机号", trigger: "blur" },
        // ],
        // code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      rules3: {
        // password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        // confirmPassword: [
        //   { required: true, message: "请再次输入密码", trigger: "blur" },
        // ],
      },
      isGetCode: false, //是否可以获取验证码
      countdown: 0, //倒计时
    };
  },
  mounted() {
    document.title = "找回密码"
    this.generateCaptcha();
  },
  methods: {
    // 生成随机验证码
    generateCaptcha() {
      const canvas = document.getElementById("randomCode");
      const ctx = canvas.getContext("2d");
      const numbers = "0123456789";
      const captchaLength = 4; // 4位数字
      const width = canvas.width;
      const height = canvas.height;

      // 清空画布
      ctx.clearRect(0, 0, width, height);

      // 设置背景颜色
      ctx.fillStyle = "#f0f0f0";
      ctx.fillRect(0, 0, width, height);

      // 随机生成验证码数字
      let captchaText = "";
      for (let i = 0; i < captchaLength; i++) {
        const num = numbers.charAt(Math.floor(Math.random() * numbers.length));
        captchaText += num;

        // 设置字体样式
        ctx.font = "30px Arial";
        ctx.fillStyle = this.getRandomColor();
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.save();

        // 绘制文字，并随机旋转
        const x = (width / captchaLength) * (i + 0.5);
        const y = height / 2;
        ctx.translate(x, y);
        ctx.rotate(((Math.random() - 0.5) * Math.PI) / 6); // 最大旋转角度30度
        ctx.fillText(num, 0, 0);
        ctx.restore();
      }

      // 绘制随机干扰线
      for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = this.getRandomColor();
        ctx.beginPath();
        ctx.moveTo(Math.random() * width, Math.random() * height);
        ctx.lineTo(Math.random() * width, Math.random() * height);
        ctx.stroke();
      }
      this.randomCode = captchaText;
      console.log("随机验证码", this.randomCode);
    },
    // 生成随机颜色
    getRandomColor() {
      const letters = "0123456789ABCDEF";
      let color = "#";
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
    // 重新生成随机验证码
    resetCode() {
      this.generateCaptcha();
    },
    // 下一步
    async nextStep(formName, active) {
      if (active == 0) {
        var success = 0;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            success = 1;
          } else {
            console.log("error submit!!");
            return false;
          }
        });
        if (success == 1) {
          if (this.ruleForm.userName == "") {
            this.$message.error("请输入账号");
            return;
          }
          if (this.ruleForm.code == "") {
            this.$message.error("请输入验证码");
            return;
          } else {
            if (this.ruleForm.code != this.randomCode) {
              this.ruleForm.code = "";
              this.$message.error("请输入正确的验证码");
              // 重新生成随机验证码
              this.generateCaptcha();
            }
            // 前端校验成功，请求接口
            else {
              await verifyUser({ phoneNumber: this.ruleForm.userName }).then(
                (res) => {
                  console.log("验证是否有该用户", res);
                  if (res.code == 200) {
                    this.active = 1;
                    this.ruleForm2.phoneNumber = this.ruleForm.userName;
                  } else {
                    this.$message.error(res.message);
                    this.ruleForm.code = "";
                    // 重新生成随机验证码
                    this.generateCaptcha();
                  }
                }
              );
            }
          }
        }
      }
      if (active == 1) {
        var success = 0;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            success = 1;
          } else {
            console.log("error submit!!");
            return false;
          }
        });
        if (success == 1) {
          if (this.ruleForm2.phoneNumber == "") {
            this.$message.error("请输入手机号");
            return;
          }
          if (this.ruleForm2.code == "") {
            this.$message.error("请输入验证码");
            return;
          }
          // 前端校验成功
          else {
            await verifyUserCode({
              phoneNumber: this.ruleForm2.phoneNumber,
              verifyCode: this.ruleForm2.code,
            }).then((res) => {
              console.log("验证验证码", res);
              if (res.code == 200) {
                this.active = 2;
              } else {
                this.$message.error(res.message);
                this.ruleForm2.code = "";
              }
            });
          }
        }
      }
      if (active == 2) {
        console.log("active", this.ruleForm3);
        var success = 0;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            success = 1;
          } else {
            console.log("error submit!!");
            return false;
          }
        });
        if (success == 1) {
          if (this.ruleForm3.password == "") {
            this.$message.error("请输入新密码");
            return;
          }
          if (this.ruleForm3.confirmPassword == "") {
            this.$message.error("请确认新密码");
            return;
          }
          if (this.ruleForm3.password != this.ruleForm3.confirmPassword) {
            this.$message.error("两次密码不一致");
          } else {
            const parmas = {
              loginName: this.ruleForm2.phoneNumber,
              password: this.ruleForm3.password,
              password2: this.ruleForm3.confirmPassword,
            };
            await resetPassword(parmas).then((res) => {
              console.log("重置密码", res);
              if (res.code == 200) {
                this.$message.success("重置密码成功");
                this.$router.push("/login");
              } else {
                this.$message.error(res.message);
                this.ruleForm3.password = "";
                this.ruleForm3.confirmPassword = "";
              }
            });
          }
        }
      }
    },
    // 获取验证码
    async getPhoneCode() {
      console.log(this.ruleForm2.phoneNumber);
      if (this.ruleForm2.phoneNumber) {
        if (this.validatePhoneNumber(this.ruleForm2.phoneNumber)) {
          await getCode({ phoneNumber: this.ruleForm2.phoneNumber }).then(
            (res) => {
              if (res.code == 200) {
                this.$message.success("验证码已发送，请注意查收！");
                this.isGetCode = true;
                this.countdown = 180;
                var timer = setInterval(() => {
                  this.countdown--;
                  if (this.countdown <= 0) {
                    clearInterval(timer);
                    this.isGetCode = false;
                  }
                }, 1000);
              }
            }
          );
        } else {
          this.$message.error("手机号格式不正确！");
        }
      } else {
        this.$message.error("请输入手机号");
      }
    },
    // 验证手机号
    validatePhoneNumber(loginName) {
      const regex = /^1[3-9]\d{9}$/;
      return regex.test(loginName);
    },
    // 返回首页
    goLogin() {
      this.$router.push("/login");
    },
  },
};
</script>
<style lang="less" scoped>
#retrievePasswordPage {
  width: 100%;
  height: 100%;
  .resetPassword {
    line-height: 30px;
    font-size: 24px;
    text-align: center;
    margin-bottom: 40px;
    font-weight: bold;
  }
  .processBar {
    width: 100%;
    height: 80px;
  }
  .content {
    width: 100%;
    height: 400px;
    padding: 0 40px;
    .code {
      width: 180px;
      display: inline-block;
    }
    #randomCode {
      width: 145px;
      margin-left: 40px;
      display: inline-block;
      background-color: rgb(13, 207, 23);
      border: 1px solid rgb(13, 207, 23);
      box-sizing: border-box;
      border-radius: 4px;
      line-height: 38px;
      cursor: pointer;
    }
    .bottomContainer {
      margin: 0 auto;
      width: 100%;
      height: 200px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .goLogin {
        width: 150px;
        height: 46px;
        line-height: 46px;
        text-align: center;
        background-color: #97979b;
        color: #fff;
        font-size: 16px;
        border: 1px solid #97979b;
        border-radius: 4px;
        margin-bottom: 20px;
        cursor: pointer;
      }
      .nextStep {
        width: 150px;
        height: 46px;
        line-height: 46px;
        text-align: center;
        background-color: #1a30de;
        color: #fff;
        font-size: 16px;
        border: 1px solid #1a30de;
        border-radius: 4px;
        margin-bottom: 20px;
        cursor: pointer;
      }
      .registerBtn {
        width: 100%;
        height: 46px;
        line-height: 46px;
        text-align: center;
        background-color: #fff;
        color: #1a30de;
        font-size: 16px;
        border: 1px solid #1a30de;
        border-radius: 4px;
        cursor: pointer;
      }
    }
    .getCode {
      width: 145px;
      margin-left: 15px;
    }
    .countdown {
      width: 145px;
      margin-left: 15px;
      display: inline-block;
      text-align: center;
      background-color: rgb(13, 207, 23);
      border: 1px solid rgb(13, 207, 23);
      box-sizing: border-box;
      border-radius: 4px;
      line-height: 38px;
    }
  }
}
/deep/.el-form-item__content {
  margin-left: 0px !important;
}
/deep/.randomCodeItem {
  .el-form-item__content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
}
</style>